# coding: utf-8
'''
Description: 
version: 1.0.0
Author: peng2.zhang
Date: 2021-05-17 14:19:31
LastEditors: peng2.zhang
LastEditTime: 2022-01-19 18:13:01
'''
import os
import logging
import traceback
from logging.config import dictConfig
from logging.handlers import TimedRotatingFileHandler
from ci_conclude.base import base_path


def getMLogger(log_name, format="[%(asctime)s] %(message)s", logpath='./logs/%s.log'):
    logger = logging.getLogger(log_name)
    log_path = os.path.join(base_path, 'logs')
    if not os.path.exists(log_path):
        os.mkdir(log_path)
    if not logger.handlers:
        logger.setLevel(logging.DEBUG)
        handler = TimedRotatingFileHandler(os.path.join(base_path, logpath % log_name), when='D')
        # handler.setLevel(logging.DEBUG)
        formatter = logging.Formatter(format)
        handler.setFormatter(formatter)
        logger.addHandler(handler)
    return logger

logger = getMLogger("main")


def getFileLogger(log_name, log_path="", format="[%(asctime)s] %(message)s"):
    logger = logging.getLogger(log_name)
    # log_path = os.path.join(logpath, log_name)
    if not os.path.exists(log_path):
        os.mkdir(log_path)
    if not logger.handlers:
        logger.setLevel(logging.DEBUG)
        handler = TimedRotatingFileHandler(os.path.join(log_path, log_name), when='D')
        # handler.setLevel(logging.DEBUG)
        formatter = logging.Formatter(format)
        handler.setFormatter(formatter)
        logger.addHandler(handler)
    return logger


def logThrown():
    logger.critical(traceback.format_exc())
    logger.critical('-'*60)


def thrownException(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except Exception as e:
            logger.info(args)
            logger.info(kwargs)
            logThrown()
            if hasattr(e, "get_return_object"):
                return e.get_return_object()
            else:
                data = ObjectDict()
                data.code = 500
                data.message = e
                data.data = None
                return data
    return wrapper
